﻿using System;
using System.Diagnostics;

using Gonte.Reflection;

namespace Gonte.Xml.Serialization
{
    /// <summary>
    /// Deserializes a primitive object from xml data
    /// </summary>
    public class XmlPrimitiveDeserializer
        : XmlObjectDeserializer
    {
        #region Constructors

        protected internal XmlPrimitiveDeserializer(Object @object)
            : base(@object)
        {
        } 

        #endregion

        #region Overridables

        protected override bool OnElement()
        {
            if (string.IsNullOrEmpty(rootElementName_)) // Root element
            {
                rootElementName_ = Reader.LocalName;
            }
            else
            {
                throw new InvalidOperationException("Primitive object can not have a child object");
            }

            return true;
        }

        protected override bool OnEndElement()
        {
            throw new InvalidOperationException("Primitive object can not have a child object");
        }

        protected override void OnAttribute()
        {
            throw new InvalidOperationException("Primitive object can not have attributes");
        }

        protected override bool OnText()
        {
            object_ = ObjectTypeConverter.ConvertValue(Reader.Value.Trim(), object_.GetType());

            Debug.WriteLine(
                string.Format(" <--- Exiting the deserializer for type: {0}",
                object_.GetType().FullName
                ));

            return false; // Stop reading
        }

        #endregion
    }
}
